package com.goldenautumn.prefabricate.wxapi

import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import com.blankj.utilcode.util.*
import com.goldenautumn.prefabricate.R
import com.goldenautumn.prefabricate.business.entity.AddressInfoVo
import com.goldenautumn.prefabricate.business.entity.WechatToken
import com.goldenautumn.prefabricate.business.user.UserViewModel
import com.google.gson.reflect.TypeToken
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import okhttp3.*
import qncx.external.common.widget.dialog.LoadingDialog
import java.io.IOException

class WXEntryActivity : AppCompatActivity(), IWXAPIEventHandler {

    private val mUserModel by viewModels<UserViewModel>()

    private var api: IWXAPI? = null

    private var mLoadingDialog: LoadingDialog = LoadingDialog()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        api = WXAPIFactory.createWXAPI(this, getString(R.string.wechatId), true)
        api?.handleIntent(intent, this)
        mLoadingDialog.onShow(supportFragmentManager.beginTransaction())
    }

    override fun onReq(p0: BaseReq?) {

    }

    //ERR_OK = 0(用户同意) ERR_AUTH_DENIED = -4（用户拒绝授权） ERR_USER_CANCEL = -2（用户取消）
    override fun onResp(resp: BaseResp?) {
        resp?.let {
            when (it.errCode) {
                0 -> {
                    var code = (resp as SendAuth.Resp).code//需要转换一下才可以
                    var isBind = SPUtils.getInstance().getBoolean("IS_BIND",false)
                    if(!isBind) mUserModel.onWeChatLogin("$code")
                    else mUserModel.bindWechat("$code")
                }
                -4 -> {
                    finish()
                }
                -2 -> {
                    finish()
                }
                else -> {
                    finish()
                }
            }
            LogUtils.d("微信结果${it.errCode}，${it.errStr}", "${it.transaction}")
        }
        SPUtils.getInstance().put("IS_BIND",false)
    }

    override fun onStop() {
        if(mLoadingDialog.isVisible) mLoadingDialog.dismiss()
        super.onStop()
    }

}